import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/products")
public class ProductServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ProductDAO productDAO = new ProductDAO();
        // 查询所有产品
        List<Product> products = productDAO.findAll();

        // 将查询结果存储到request对象中
        request.setAttribute("products", products);

        // 转发请求到JSP页面
        request.getRequestDispatcher("/home.jsp").forward(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        ProductDAO productDAO = new ProductDAO();
        // 接收参数
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        String price = request.getParameter("price");

        Product product = new Product();
        // 设置属性值
        product.setName(name);
        product.setDescription(description);
        product.setPrice(Double.parseDouble(price));
        boolean flag = productDAO.addProduct(product);

        String msg = null;
        if (flag) {
            msg = "添加成功";
        }
        else {
            msg = "添加失败";

        }
        request.setAttribute("msg", msg);// 将消息存储到request对象中
        List<Product> products = productDAO.findAll();// 查询所有产品

        request.setAttribute("products", products);// 将查询结果存储到request对象中

        request.getRequestDispatcher("/home.jsp").forward(request, response);// 转发请求到JSP页面



    }
}